package swim.sessionbeans;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.ejb.Stateless;
import javax.persistence.*;

import org.jboss.ejb3.annotation.RemoteBinding;

import swim.entitybeans.RegisteredUser;
import swim.entitybeans.Admin;



@Stateless
@RemoteBinding(jndiBinding="Authentication/remote")
public class Authentication implements AuthenticationRemote{
	@PersistenceContext(unitName="swim")
	private EntityManager manager;
	
	/*Questa funzione permette ad un utente di autenticarsi con lo username o l'email*/
	public RegisteredUser AuthenticateUser (String emailOrUsername, String password){
		try{
			Query q = manager.createQuery("FROM RegisteredUser u WHERE u.email =:emailOrUsername OR u.username =:emailOrUsername");
			q.setParameter("emailOrUsername", emailOrUsername);
			RegisteredUser user = (RegisteredUser) q.getSingleResult();
			MessageDigest md = MessageDigest.getInstance("MD5");  //START MD5 conversion
			md.update(password.getBytes(),0,password.length());  //..
			String md5password = new BigInteger(1,md.digest()).toString(16); // password in md5 in md5password
			if (user == null) {
				return null;
			}
			if (user.getPassword().equals(md5password)) {
				return user;
			}
			else {
				return null;
			}
		}
		catch (EntityNotFoundException exc) {
			exc.printStackTrace();
			return null;
			/* non sono state trovate entita' */
			}
		catch (NonUniqueResultException exc) {
			exc.printStackTrace();
			return null;
			/* e' stata trovata piu' di una entita' */
		} 
		catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (Exception exc) { 
			return null;
		}
	}	
	
	 public Admin AuthenticateAdmin(String emailOrUsername, String password){
		 try{		 	
			Query q = manager.createQuery("FROM Admin u WHERE u.email =:emailOrUsername OR u.username =:emailOrUsername");
			q.setParameter("emailOrUsername", emailOrUsername);
			Admin admin = (Admin) q.getSingleResult();
			MessageDigest md = MessageDigest.getInstance("MD5");  //START MD5 conversion
			md.update(password.getBytes(),0,password.length());  //..
			String md5password = new BigInteger(1,md.digest()).toString(16); // password in md5 in md5password
			if (admin == null) {
				return null;
			}
			if (admin.getPassword().equals(md5password)) {
				return admin;
			}
			else {
				return null;
			}
		 }
		 catch (EntityNotFoundException exc) { 
			return null;
			/* non sono state trovate entita' */
		 } catch (NonUniqueResultException exc) { 
			return null;
			/* e' stata trovata piu' di una entita' */
		 } catch (Exception exc) { 
			return null;
		 }		 
	 }
}
